$(function () {
    let inputUtil = new Input_util();
    inputUtil.popUpsView();
    inputUtil.popUpsInsert();
    let popUpsDown = $(".pop-ups-down");
    let recycle = $(".recycle");
    popUpsDown.on("click", function () {
        $(".recycle-bin-window").css("display", "none")
    })
    recycle.on("click", function () {
        $(".recycle-bin-window").css("display", "block")
        console.log(1)
    })


    $(".search-img").on("click", function () {
        const val = $(".search-input input").val()
        window.location.href = "/www.xiaomi.com/background/home?menuId=102&name=" + val;
    })
    let commodity = new Commodity();
    $(".leave").on("click", function () {
        commodity.updateAllSelectedStatus($(this).attr("commodity-id"), 2).then(res => {
            console.log(res)
            location.reload();
        })
    })

    $(".shelves").on("click", function () {
        commodity.updateAllSelectedStatus($(this).attr("commodity-id"), 0).then(res => {
            console.log(res)
            location.reload();
        })
    })

    $(".select").on("click", function () {
        console.log($(this).val());
        window.location.href = "/www.xiaomi.com/background/home?menuId=102&selectShelves=" + $(".select-shelves").val();
    })

    $(".view").on("click", function () {
        let commodity = new Commodity();
        let commoditySpecification = new Commodity_specification();
        let commodityInsuranceType = new Commodity_insurance_type();
        commodity.getCommodityById($(this).attr("commodity-id")).then(res => {
            let commodityJson = JSON.parse(res);
            console.log(commodityJson)
            $(".pop-ups").attr("commodity-id", commodityJson.commodityId)
            $(".window-commodity-basic-information .name").text(commodityJson.commodityName)
            $(".window-update-commodity-name input").val(commodityJson.commodityName)
            $(".window-update-commodity-price input").val((commodityJson.commodityPrice).toFixed(2))
            $(".window-update-commodity-discounte input").val(commodityJson.commodityDiscount)

            $(".window-commodity-images").empty()
            $(".window-commodity-gifts").empty()
            $(".window-commodity-details-images").empty()
            $(".window-commodity-details-video").empty();
            $(".window-commodity-specifications").empty();
            $(".window-commodity-details-parameter").empty();
            $(".window-commodity-type").empty()
            $(".window-commodity-serve").empty();

            $(".window-commodity-basic-information .keywords-text").empty()
            $(".pop-ups-content").attr("commoditie-id", commodityJson.commodityId)
            if (parseInt(commodityJson.commodityDiscount) !== 0) {
                if (parseInt(commodityJson.commodityDiscount) === 6) {
                    $(".window-commodity-discount-price").text((parseFloat(commodityJson.commodityPrice) * 0.6).toFixed(2) + "元起")
                } else if (parseInt(commodityJson.commodityDiscount) === 7) {
                    $(".window-commodity-discount-price").text((parseFloat(commodityJson.commodityPrice) * 0.7).toFixed(2) + "元起")
                } else if (parseInt(commodityJson.commodityDiscount) === 8) {
                    $(".window-commodity-discount-price").text((parseFloat(commodityJson.commodityPrice) * 0.8).toFixed(2) + "元起")
                } else if (parseInt(commodityJson.commodityDiscount) === 9) {
                    $(".window-commodity-discount-price").text((parseFloat(commodityJson.commodityPrice) * 0.9).toFixed(2) + "元起")
                }
                $(".window-commodity-original-price").text(parseFloat(commodityJson.commodityPrice))
            } else {
                $(".window-commodity-discount-price").text((commodityJson.commodityPrice).toFixed(2) + "元起")
            }
            $(".window-commodity-product-description textarea").text(commodityJson.commodityDescription)
            //商品参数
            if (commodityJson.commodityParameterList.length === 0){
            $(".window-commodity-details-parameter").append(`
<div class="not-context"><img src="http://localhost:8083/resource_packs/images/not_context.png" alt="无详细内容">
<a> 无详细内容 </a></div>`)
            }
            for (const commodityParameterJson of commodityJson.commodityParameterList) {
                let html = `<div>`;
                if (commodityParameterJson.parameterImages !== undefined){
                    html += `<img src="http://localhost:8083/resource_packs/images/${commodityParameterJson.parameterImages}" 
style="width: 100%;" alt="商品参数图片">`
                }
                if (commodityParameterJson.parameterTitle !== undefined){
                    html+=`<p class="window-commodity-parameter-title">${commodityParameterJson.parameterTitle}
<button class="window-remove-commodity-parameter-button" parameter-id="${commodityParameterJson.parameterId}">删除</button></p>`
                }
                if (commodityParameterJson.parameterContext){
                    html+=`<span class="window-commodity-parameter-context">${commodityParameterJson.parameterContext}</span></div>`
                }
                $(".window-commodity-details-parameter").append(html)
            }
            
            //商品详细视频
            if (commodityJson.commodityDetails.detailsVideo === undefined){
                $(".window-add-commodity-details").append(`<label class="window-add-commodity-details-video"
                                   style="height: 150px;text-align: center;line-height: 200px;cursor: pointer;">
                                <div style="height: 100%;display: grid;text-align: center;">
                                    <img src="http://localhost:8083/resource_packs/images/add_commodity_img.png"
                                         alt="添加详细视频" style="margin: auto;">
                                    <span style="height: 10px;line-height: 20px;text-align: center;">
                                    商品详细视频添加
                                </span>
                                    <input type="file" name="file" class="upload-details-video" style="display: none;">
                                </div>
                            </label>`)
            }
            if (commodityJson.commodityDetails.detailsVideo !== undefined) {
                //商品详细视频
                $(".window-commodity-details-video").append(`
            <div>
            <video width="100%" height="100%" controls>
            <source src="http://localhost:8083/resource_packs/media/${commodityJson.commodityDetails.detailsVideo}"
             type="video/ogg">
            </video>
            <img src="http://localhost:8083/resource_packs/images/remove_commodity_img.png" 
            video-name="${commodityJson.commodityDetails.detailsVideo}"
                     class="window-remove-commodity-details-video" alt="删除详细视频"></div>`)
            }
            if (commodityJson.commodityDetails.detailsImages !== undefined){
                //商品详细图片
                $(".window-add-commodity-details-img").attr("details-images", commodityJson.commodityDetails.detailsImages)
                let commodityImgs = commodityJson.commodityDetails.detailsImages.split(",");
                for (const commodityImg of commodityImgs) {
                    $(".window-commodity-details-images").append(`
                    <div>
                    <img src="http://localhost:8083/resource_packs/images/${commodityImg}"
                     class="window-commodity-details-img" alt="商品详细图片">
                    <span><img src="http://localhost:8083/resource_packs/images/remove_commodity_img.png"
                     img-name="${commodityImg}"
                     class="window-remove-commodity-details" alt="删除详细图片"></span></div>`)
                }
            }
            //商品详细图片
            if (commodityJson.commodityDetails.detailsImages === undefined && commodityJson.commodityDetails.detailsVideo === undefined) {
                $(".window-commodity-details-images").append(`
<div class="not-context"><img src="http://localhost:8083/resource_packs/images/not_context.png" alt="无详细内容">
<a> 无详细内容 </a></div>`)
            }
            //赠品
            if (commodityJson.gifts !== undefined) {
                $(".window-commodity-gifts").append(`
<img src="http://localhost:8083/resource_packs/images/${commodityJson.gifts.commodity.commodityImages}" alt="赠品图片"/>
<div class="context">
<div><a class="title">赠品</a><a class="inventory-title">库存 : </a><input class="inventory" placeholder="赠品库存" 
 commodity-gifts-id="${commodityJson.gifts.commodityGiftsId}"
 value="${commodityJson.gifts.giftsNumber}"></div>
<div style="display: inline-flex">
<span class="name">${commodityJson.gifts.commodity.commodityName}</span>
<button class="remove-gitfts-button" commodity-gifts-id="${commodityJson.gifts.commodityGiftsId}">删除</button>
</div>
</div>`)
            } else {
                //没有赠品可以选择赠品
                commodity.queryCommodityGiftsAndCommodity().then(res => {
                    let commodityGiftsJson = JSON.parse(res);
                    let selectGifts = "<div class='select-gitfts'><span>赠品 : </span><select class='select-gitfts-input'>"
                    for (const commodityGifts of commodityGiftsJson) {
                        selectGifts += "<option commodity-gifts-id='" + commodityGifts.commodityGiftsId + "' " +
                            "commoditie-id='" + commodityGifts.commodity.commodityId + "' " +
                            "value='" + commodityGifts.commodity.commodityName + "'>" +
                            commodityGifts.commodity.commodityName + "</option>"
                    }
                    selectGifts += "</select></div>"
                    $(".window-commodity-gifts").html(selectGifts)
                })
            }

            $(".window-commodity-type").append(`${commodityJson.type.category.model.modelName}
              >  ${commodityJson.type.category.categoryName}
                >  ${commodityJson.type.className}`)

            $(".window-commodity-serve").append(`<span>是否售后</span>
<input type="radio" name="is-after-sales" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isAfterSales === 0 ? 'checked' : ''}>是
<input type="radio" name="is-after-sales" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isAfterSales === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否支持企业信息</span>
<input type="radio" name="is-company-information" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isCompanyInformation === 0 ? 'checked' : ''}>是
<input type="radio" name="is-company-information" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isCompanyInformation === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否小米发货</span>
<input type="radio" name="is-mi-shipments" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isMiShipments === 0 ? 'checked' : ''}>是
<input type="radio" name="is-mi-shipments" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isMiShipments === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否支持7天价格保护</span>
<input type="radio" name="is-price-protection" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isPriceProtection === 0 ? 'checked' : ''}>是
<input type="radio" name="is-price-protection" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isPriceProtection === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否支持7天无理由退货</span>
<input type="radio" name="is-return" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isReturn === 0 ? 'checked' : ''}>是
<input type="radio" name="is-return" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isReturn === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否小米自营</span>
<input type="radio" name="is-self-employed" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isSelfEmployed === 0 ? 'checked' : ''}>是
<input type="radio" name="is-self-employed" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isSelfEmployed === 1 ? 'checked' : ''}>否`)
            $(".window-commodity-serve").append(`<span>是否支持运费说明</span>
<input type="radio" name="is-shipping-instructions" class="window-update-commodity-serve" value="0" ${commodityJson.commodityServe.isShippingInstructions === 0 ? 'checked' : ''}>是
<input type="radio" name="is-shipping-instructions" class="window-update-commodity-serve" value="1" ${commodityJson.commodityServe.isShippingInstructions === 1 ? 'checked' : ''}>否`)


            //商品规格类别
            let commoditySpecificationType = new Commodity_specification_type();
            commoditySpecificationType.getAllCommoditySpecificationTypes().then(res => {
                let commoditySpecificationTypeJson = JSON.parse(res);
                for (const commoditySpecificationType of commoditySpecificationTypeJson) {
                    //选择新增商品规格类别
                    $(".window-update-commodity-specifications select").append(`
<option specification-type-id="${commoditySpecificationType.specificationTypeId}">
${commoditySpecificationType.specificationTypeName}</option>`)
                }
            })


            //规格类别
            for (let i = 0; i < commodityJson.commoditySpecificationTypeList.length; i++) {
                $(".window-commodity-specifications").append(`<div class="commodity-specification-row">
<p class="commodity-specification-title">${commodityJson.commoditySpecificationTypeList[i].specificationTypeName}</p>
<div class="commodity-specification-context">
</div>
</div>`)
                //选择删除商品规格类别
                $(".window-update-commodity-specifications-type select").append(`
<option specification-type-id="${commodityJson.commoditySpecificationTypeList[i].specificationTypeId}">
${commodityJson.commoditySpecificationTypeList[i].specificationTypeName}</option>`)
                //商品规格
                for (const commoditySpecificationJson of commodityJson.commoditySpecificationTypeList[i].commoditySpecification) {
                    $($(".commodity-specification-context")[i]).append(`
<span specification-id="${commoditySpecificationJson.specificationId}"
 title="${commoditySpecificationJson.addPrice === undefined ? "免费" : "增加" + commoditySpecificationJson.addPrice + "元"}">
${commoditySpecificationJson.specificationName}
</span>`)
                }
            }
            //查询全部商品保险
            commodityInsuranceType.getAllCommodityInsuranceTypes().then(res => {
                let resCommodityInsuranceJson = JSON.parse(res);
                console.log(resCommodityInsuranceJson)
                for (const commodityInsurance of resCommodityInsuranceJson) {
                    $(".window-update-commodity-insurance select").append(`
<option insurance-type-id="${commodityInsurance.insuranceTypeId}">${commodityInsurance.insuranceTypeTitle}</option>`)
                }
            })
            //关键字
            for (const keyword of commodityJson.keywords.split(/[,｜]/)) {
                $(".window-commodity-basic-information .keywords-text").append(`<span class="keyword" title="${keyword}" 
commoditie-id="${commodityJson.commodityId}" >${keyword}</span>`)
            }
            //商品图片
            let commodityImages = commodityJson.commodityImages.split(",");
            if (commodityImages.length === 1) {
                for (const commodityImage of commodityImages) {
                    $(".window-commodity-images").append(`
<div>
<img src="http://localhost:8083/resource_packs/images/${commodityImage}" alt="商品图片" class="window-commodity-img">
</div>
`)
                }
            } else {
                for (const commodityImage of commodityImages) {
                    $(".window-commodity-images").append(`<div>
<img src="http://localhost:8083/resource_packs/images/${commodityImage}" alt="商品图片" class="window-commodity-img">
<img src="http://localhost:8083/resource_packs/images/remove_commodity_img.png" alt="删除此图片" class="delete-img" 
commoditie-id="${commodityJson.commodityId}" 
 commodity-image-name="${commodityImage}" >
</div>`)
                }
            }

            //商品保险
            for (let z = 0; z < commodityJson.commodityInsuranceTypeList.length; z++) {
                $(".window-commodity-insurances").append(`<div class="commodity-insurances-row">
<p class="commodity-insurances-title">
<img src="http://localhost:8083/resource_packs/images/${commodityJson.commodityInsuranceTypeList[z].insuranceTypeLogo}" alt="保险图标">
<span>${commodityJson.commodityInsuranceTypeList[z].insuranceTypeTitle}</span>
</p>
<div class="commodity-insurances-context">

</div>
</div>`)
                for (const commodityInsurance of commodityJson.commodityInsuranceTypeList[z].commodityInsurances) {
                    $($(".commodity-insurances-context")[z]).append(`<span insurance-id="${commodityInsurance.insuranceId}"
 title="${commodityInsurance.addPrice}元  保险详细:${commodityInsurance.insuranceContext}">
${commodityInsurance.insuranceTitle}</span>`)
                }
            }
            if (commodityImages.length !== 5) {
                $(".window-commodity-images").append(`<div><a class="add-commodity-img">
<img src="http://localhost:8083/resource_packs/images/add_commodity_img.png" alt="新增商品图片" >
<input type="file" name="file" class="upload-commodity-image" style="display: none;" commodity-image-name="${commodityJson.commodityImages}" 
commoditie-id="${commodityJson.commodityId}">
</a></div>`)
            }
            //修改商品服务
            $(".window-update-commodity-serve").on("click",function () {
                let commodityServe = {
                    isAfterSales:$('input[name="is-after-sales"]:checked').val(),
                    isCompanyInformation:$('input[name="is-company-information"]:checked').val(),
                    isMiShipments:$('input[name="is-mi-shipments"]:checked').val(),
                    isPriceProtection:$('input[name="is-price-protection"]:checked').val(),
                    isReturn:$('input[name="is-return"]:checked').val(),
                    isSelfEmployed:$('input[name="is-self-employed"]:checked').val(),
                    isShippingInstructions:$('input[name="is-shipping-instructions"]:checked').val(),
                    commodityId:$(".pop-ups").attr("commodity-id")
                }
                commodity.updateByCommodityServe(commodityServe).then(res=>{
                    console.log(res)
                })
            })
            //商品参数
            $(".window-remove-commodity-parameter-button").on("click",function () {
                let parameterId = $(this).attr("parameter-id");
                console.log(parameterId)
                commodity.deleteCommodityParameterById(parameterId).then(res=>{
                    console.log(res)
                    location.reload();
                })
            })
            //新增保险
            $(".window-update-commodity-insurance input").on("keyup", function () {
                if (event.keyCode === 13) {
                    let specificationsTypeId = $(".window-update-commodity-insurance option:selected")
                        .attr("insurance-type-id");
                    let insuranceNameValue = $(".window-update-commodity-insurance input").val();
                    let insurancePriceValue = $(".window-add-commodity-insurance-price input").val();
                    let insuranceDetailedValue = $(".window-add-commodity-insurance-detailed input").val();
                    let commodityId = $(".pop-ups").attr("commodity-id");

                    if (inputUtil.isEmpty(insuranceDetailedValue) || inputUtil.isEmpty(insuranceDetailedValue)
                        || inputUtil.isEmpty(insuranceDetailedValue)) {
                        alert("不能为空!")
                    } else {
                        let commodityInsurance = {
                            insuranceTitle: insuranceNameValue,
                            addPrice: insurancePriceValue,
                            insuranceContext: insuranceDetailedValue,
                            insuranceTypeId: specificationsTypeId,
                            commodityId: commodityId
                        }
                        commodity.addCommodityInsurance(commodityInsurance).then(res => {
                            console.log(res)
                            location.reload();
                        })
                    }
                }
            })
            //删除商品详细视频
            $(".window-remove-commodity-details-video").on("click",function () {
                let commodityId = $(".pop-ups").attr("commodity-id");
                let videoName = $(this).attr("video-name");
                commodity.deleteVideo(videoName).then(res=>{
                    commodity.updateDetailsVideoByCommodityId(commodityId,"").then(res => {
                        console.log(res)
                        location.reload()
                    })
                })
            })
            //删除商品详细图片
            $(".window-remove-commodity-details").on("click", function () {
                let detailsImages = commodityJson.commodityDetails.detailsImages;
                let thisImg = $(this).attr("img-name")
                let commodityId = $(".pop-ups").attr("commodity-id");
                if (detailsImages.includes(thisImg+",")) {
                    // 删除 "1705631563501_鸣潮.jfif" 及其前面的逗号
                    detailsImages = detailsImages.replace(thisImg+",", "");
                } else if (detailsImages.includes(","+thisImg)){
                    // 否则，删除 "1705630591350_iTab-285e6x.png" 后面的逗号
                    detailsImages = detailsImages.replace(","+thisImg, "");
                }else{
                    //直接删除
                    detailsImages = detailsImages.replace(thisImg, "");
                }
                // 文件上传成功后的处理 修改图片名称
                commodity.deleteCommodityImage(thisImg).then(res => {
                    commodity.updateDetailsImagesByCommodityId(commodityId, detailsImages).then(res => {
                        console.log(res)
                        location.reload()
                    })
                });

            })
            //双击删除规格
            $(".commodity-specification-context span").on("dblclick", function () {
                let specificationId = $(this).attr("specification-id");
                let commodityId = $(".pop-ups").attr("commodity-id");
                commoditySpecification.deleteCommoditySpecificationByIds(specificationId, commodityId).then(res => {
                    console.log(res)
                    location.reload()
                })
            })
            //删除商品保险
            $(".commodity-insurances-context span").on("dblclick", function () {
                let insuranceId = $(this).attr("insurance-id");
                let commodityId = $(".pop-ups").attr("commodity-id");
                commodity.deleteCommodityInsuranceByCommodityIdAndInsuranceId(commodityId, insuranceId).then(res => {
                    console.log(res)
                    location.reload();
                })
            })
            //修改名称
            $(".window-update-commodity-name input").on("keyup", function () {
                if (event.keyCode === 13) {
                    let nameValue = $(this).val();
                    let commodityId = $(".pop-ups").attr("commodity-id");
                    commodity.updateCommodityNameById(commodityId, nameValue).then(res => {
                        console.log(res)
                        location.reload()
                    })
                }
            })
            //修改价格
            $(".window-update-commodity-price input").on("keyup", function () {
                if (event.keyCode === 13) {
                    let priceValue = $(this).val();
                    let commodityId = $(".pop-ups").attr("commodity-id");
                    commodity.updateCommodityPriceById(commodityId, priceValue).then(res => {
                        console.log(res)
                        location.reload()
                    })

                }
            })
            //修改折扣
            $(".window-update-commodity-discounte input").on("keyup", function () {
                if (event.keyCode === 13) {
                    let discountValue = $(this).val();
                    console.log(discountValue)
                    if ((6 > parseInt(discountValue) || parseInt(discountValue) > 9) && parseInt(discountValue) !== "") {
                        alert("折扣不能小于6、不能大于9")
                    } else {
                        let commodityId = $(".pop-ups").attr("commodity-id");
                        commodity.updateCommodityDiscountById(commodityId, discountValue).then(res => {
                            console.log(res)
                            location.reload()
                        })
                    }
                }
            })
            //删除规格类别下全部规格
            $(".window-remove-commodity-specifications-type").on("click", function () {
                let specificationsType = $(".window-update-commodity-specifications-type option:selected")
                    .attr("specification-type-id");
                let commodityId = $(".pop-ups").attr("commodity-id");
                commoditySpecification.deleteCommoditySpecification(specificationsType, commodityId).then(res => {
                    console.log(res)
                    location.reload();
                })
            })
            //新增商品规格
            $(".window-update-commodity-specifications input").on("keyup", function () {
                if (event.keyCode === 13) {
                    //规格
                    let specificationsInput = $(this).val();
                    //规格价格
                    let specificationsPrice = $(".window-add-commodity-specifications-price input").val();
                    //规格类别Id
                    let specificationsTypeId = $(".window-update-commodity-specifications option:selected")
                        .attr("specification-type-id");
                    //商品Id
                    let commoditieId = $(".pop-ups-content").attr("commoditie-id");
                    commoditySpecification.insertCommoditySpecification(commoditieId,
                        specificationsPrice, specificationsTypeId, specificationsInput).then(res => {
                        console.log(res)
                        location.reload()
                    })
                }
            })
            //新增商品规格类别
            $(".window-update-commodity-specifications-type input").on("keyup", function () {
                if (event.keyCode === 13) {
                    commoditySpecificationType.insertCommoditySpecificationType($(this).val()).then(res => {
                        console.log(res)
                        location.reload()
                    })
                }
            })
            //添加赠品
            $(document).on("change", ".select-gitfts-input", function () {
                let commodityId = $(".pop-ups").attr("commodity-id");
                let giftsId = $(this).find(":selected").attr("commodity-gifts-id");
                commodity.updateCommodityGiftsById(commodityId, giftsId).then(res => {
                    console.log(res)
                    location.reload();
                })
            });
            //删除赠品
            $(".remove-gitfts-button").on("click", function () {
                let commodityId = $(".pop-ups").attr("commodity-id");
                commodity.updateCommodityGiftsById(commodityId).then(res => {
                    console.log(res)
                    location.reload();
                })
            })
            //回车修改赠品库存
            $('.inventory').on('keyup', function (event) {
                if (event.keyCode === 13) { // 判断按下的是否是回车键
                    let inventory = $(this).val().trim();
                    let commodityGiftsId = $(this).attr("commodity-gifts-id");
                    commodity.updateGiftsNumberById(commodityGiftsId, inventory).then(res => {
                        console.log(res)
                        location.reload()
                    })
                }
            });
            $('.add-commodity-img').on('mouseenter', function () {
                // 鼠标悬浮时执行的操作
                $(".add-commodity-img img").attr('src', 'http://localhost:8083/resource_packs/images/add_commodity_insurance.png');
            });
            //上传商品视频
            $(".window-add-commodity-details-video").on("click",function (e) {
                e.preventDefault();
                // 创建并触发一个模拟的点击事件
                let clickEvent = new MouseEvent('click', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                $('.upload-details-video')[0].dispatchEvent(clickEvent);
            })
            //上传商品参数图片
            $(".window-add-parameter-image").on("click",function (e) {
                e.preventDefault();
                // 创建并触发一个模拟的点击事件
                let clickEvent = new MouseEvent('click', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                $('.upload-parameter-image')[0].dispatchEvent(clickEvent);
            })
            //上传商品图片
            $('.add-commodity-img').on('click', function (e) {
                e.preventDefault();
                // 创建并触发一个模拟的点击事件
                let clickEvent = new MouseEvent('click', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                $('.upload-commodity-image')[0].dispatchEvent(clickEvent);
            });
            //上传详细图片
            $(".window-add-commodity-details-img").on("click", function (e) {
                e.preventDefault();
                // 创建并触发一个模拟的点击事件
                let clickEvent = new MouseEvent('click', {
                    view: window,
                    bubbles: true,
                    cancelable: true
                });
                $('.upload-details-image')[0].dispatchEvent(clickEvent);
            })
            // 修改关键字 添加双击事件
            $(".keywords-text .keyword").on("dblclick", function () {
                let keywords = commodityJson.keywords;
                let myKeywords = $(this).text()
                let afterUpdating = "";
                if (commodityJson.keywords.split("｜").length > 1) {
                    if (keywords.includes("｜" + myKeywords)) {
                        afterUpdating = keywords.replace("｜" + myKeywords, "")
                    }
                    console.log(keywords.includes(myKeywords + "｜"))
                    if (keywords.includes(myKeywords + "｜")) {
                        afterUpdating = keywords.replace(myKeywords + "｜", "")
                    }
                    commodity.updatedKeywordsById(afterUpdating, $(this).attr("commoditie-id")).then(res => {
                        console.log(res)
                        location.reload()
                    })
                }
            });
            //添加关键字
            $('.add-keyword').on('keyup', function (event) {
                if (event.keyCode === 13) { // 判断按下的是否是回车键
                    let keyword = $(this).val().trim();
                    if (keyword !== '') { // 确保输入框不为空
                        let originalKeywords = commodityJson.keywords;
                        commodity.updatedKeywordsById(originalKeywords + "｜" + keyword,
                            $(".pop-ups-content").attr("commoditie-id")).then(res => {
                            console.log(res)
                            location.reload()
                        })
                    }
                }
            });
            //回车
            $('.window-commodity-product-description textarea').on('keyup', function (event) {
                if (event.keyCode === 13) { // 判断按下的是否是回车键
                    let description = $(this).val().trim();
                    console.log(description)
                    commodity.updateCommodityDescriptionById($(".pop-ups-content").
                    attr("commoditie-id"), description).then(res => {
                        console.log(res)
                        location.reload();
                    })
                }
            });
            let commodityParameterImageFiles = null;
            //上传商品参数
            $(".upload-parameter-image").on("change",function () {
                // 检查是否已选择视频文件
                if (!this.files || !this.files[0]) {
                    return;
                }
                // 获取选中的文件信息
                let file = this.files[0];
                commodityParameterImageFiles = file;
                let fileName = file.name;
                let fileSize
                    = file.size;
                let fileType = file.type;
                console.log(fileName)
                if (fileType.indexOf('image/') === 0 && fileSize < 500 * 1024 * 1024) {

                }else{
                    // 将文件信息显示在页面上
                    alert('请选择图片文件，且文件大小不能超过500MB！');
                }
            })
            $(".window-add-commodity-parameter-title input").on("keyup",function (event) {
                if (event.keyCode === 13) { // 判断按下的是否是回车键
                    let commodityId = $(".pop-ups").attr("commodity-id");
                    if ($(".window-add-commodity-parameter-title input").val() !== ""){
                        // 调用 addCommodityImage() 函数上传文件
                        if (commodityParameterImageFiles === null){
                            let commodityParameter = {
                                parameterTitle:$(".window-add-commodity-parameter-title input").val(),
                                parameterContext:$(".window-add-commodity-parameter-context textarea").val(),
                                commodityId:commodityId
                            }
                            // 文件上传成功后的处理 新增商品规格
                            commodity.addCommodityParameter(JSON.stringify(commodityParameter)).then(res => {
                                console.log(res)
                                location.reload()
                            })
                        }else{
                            commodity.addCommodityImage(commodityParameterImageFiles).then(function (response) {
                                let commodityParameter = {
                                    parameterImages:response,
                                    parameterTitle:$(".window-add-commodity-parameter-title input").val(),
                                    parameterContext:$(".window-add-commodity-parameter-context textarea").val(),
                                    commodityId:commodityId
                                }
                                // 文件上传成功后的处理 新增商品规格
                                commodity.addCommodityParameter(JSON.stringify(commodityParameter)).then(res => {
                                    console.log(res)
                                    location.reload()
                                })
                            })
                        }
                    }
                }
            })
            //上传商品详细视频
            $(".upload-details-video").on("change",function () {
                // 检查是否已选择视频文件
                if (!this.files || !this.files[0]) {
                    return;
                }
                // 获取选中的文件信息
                let file = this.files[0];
                let fileName = file.name;
                let fileSize
                    = file.size;
                let fileType = file.type;
                let commodityId = $(".pop-ups").attr("commodity-id");
                // 判断文件是否是图片，且文件大小不超过1200MB
                if (fileType.indexOf('video/') === 0 && fileSize < 1200 * 1024 * 1024) {
                    // 调用 addCommodityImage() 函数上传文件
                    commodity.addCommodityVideo(file).then(function (response) {
                        // 文件上传成功后的处理 修改图片名称
                        commodity.updateDetailsVideoByCommodityId(commodityId,response).then(res => {
                            console.log(res)
                            location.reload()
                        })
                    })
                } else {
                    // 将文件信息显示在页面上
                    alert('请选择视频文件，且文件大小不能超过1200MB！');
                }
            })
            // 上传商品图片
            $('.upload-commodity-image').on('change', function () {
                // 获取选中的文件信息
                let file = this.files[0];
                let fileName = file.name;
                let fileSize = file.size;
                let fileType = file.type;
                let newImagesName = $(this).attr("commodity-image-name");
                let commoditieId = $(this).attr("commoditie-id");
                // 判断文件是否是图片，且文件大小不超过500MB
                if (fileType.indexOf('image/') === 0 && fileSize < 500 * 1024 * 1024) {
                    // 调用 addCommodityImage() 函数上传文件
                    commodity.addCommodityImage(file).then(function (response) {
                        // 文件上传成功后的处理 修改图片名称
                        commodity.updateCommodityImage(response + "," + newImagesName,
                            commoditieId).then(res => {
                            console.log(res)
                            location.reload()
                        })
                    })
                } else {
                    // 将文件信息显示在页面上
                    alert('请选择图片文件，且文件大小不能超过500MB！');
                }
            });
            // 上传商品详细图片
            $('.upload-details-image').on('change', function () {
                // 获取选中的文件信息
                let file = this.files[0];
                let fileName = file.name;
                let fileSize
                    = file.size;
                let fileType = file.type;
                let commodityId = $(".pop-ups").attr("commodity-id");
                let newDetailsImagesName = $(".window-add-commodity-details-img").attr("details-images");
                console.log(newDetailsImagesName)
                console.log(commodityId)
                // 判断文件是否是图片，且文件大小不超过500MB
                if (fileType.indexOf('image/') === 0 && fileSize < 500 * 1024 * 1024) {
                    // 调用 addCommodityImage() 函数上传文件
                    commodity.addCommodityImage(file).then(function (response) {
                        if (newDetailsImagesName !== undefined) {
                            // 文件上传成功后的处理 修改图片名称
                            commodity.updateDetailsImagesByCommodityId(commodityId, newDetailsImagesName + "," + response).then(res => {
                                console.log(res)
                                location.reload()
                            })
                        } else {
                            // 文件上传成功后的处理 修改图片名称
                            commodity.updateDetailsImagesByCommodityId(commodityId, response).then(res => {
                                console.log(res)
                                location.reload()
                            })
                        }
                    })

                } else {
                    // 将文件信息显示在页面上
                    alert('请选择图片文件，且文件大小不能超过500MB！')
                }
            });
            // 使用 on() 方法绑定鼠标离开事件
            $('.add-commodity-img').on('mouseleave', function () {
                // 鼠标离开时执行的操作
                $(".add-commodity-img img").attr('src', 'http://localhost:8083/resource_packs/images/add_commodity_img.png');
            });
            //删除商品图片
            $(".delete-img").on("click", function () {
                let targetValue = $(this).attr("commodity-image-name");
                let commoditieId = $(this).attr("commoditie-id");
                let originalString = commodityJson.commodityImages;
                // 使用 split() 方法将原始字符串拆分成数组
                let originalArray = originalString.split(",");
                console.log(commodityJson.commodityImages)
                console.log(targetValue)

                console.log(originalArray.length)
                let imgs = commodityJson.commodityImages;
                if (originalArray.length > 1) {
                    if (imgs.includes(targetValue+",")) {
                        // 删除 "1705631563501_鸣潮.jfif" 及其前面的逗号
                        imgs = imgs.replace(targetValue+",", "");
                    } else if (imgs.includes(","+targetValue)){
                        // 否则，删除 "1705630591350_iTab-285e6x.png" 后面的逗号
                        imgs = imgs.replace(","+targetValue, "");
                    }else{
                        //直接删除
                        imgs = imgs.replace(targetValue, "");
                    }
                    commodity.deleteCommodityImage(targetValue).then(res => {
                        console.log(res)
                        commodity.updateCommodityImage(imgs,
                            commoditieId).then(res => {
                            console.log(res)
                            location.reload()
                        })
                    })
                } else {
                    alert("无法删除更多图片了!")
                }
            })
        })
    })
    findCategoryByModelId();
    $(".window-add-commodity-model").on("change",function () {
        findCategoryByModelId();
    })
    $(".window-add-commodity-category").on("change",function () {
        findClassByCategoryId();
    })
    function findCategoryByModelId() {
        $(".window-add-commodity-category").empty();
        let selectedOption = $('.window-add-commodity-model option:selected').val();
        let commodity = new Commodity();
        commodity.findCategoryByModelId(selectedOption).then(res=>{
            let categoryJson = JSON.parse(res)
            for (const category of categoryJson) {
                $(".window-add-commodity-category").append(`<option value="${category.categoryId}">
${category.categoryName}</option>`)
            }
            findClassByCategoryId();
        })
    }
    function findClassByCategoryId() {
        $(".window-add-commodity-class").empty()
        let commodity = new Commodity();
        let selectedOption = $(".window-add-commodity-category option:selected").val();
        commodity.findClassByCategoryId(selectedOption).then(res=>{
            let classJson = JSON.parse(res);
            console.log(classJson)
            for (const type of classJson) {
                $(".window-add-commodity-class").append(`<option value="${type.classId}">${type.className}</option>`)
            }
        })
    }
    //商品规格类别
    let commoditySpecificationType = new Commodity_specification_type();
    commoditySpecificationType.getAllCommoditySpecificationTypes().then(res => {
        let commoditySpecificationTypeJson = JSON.parse(res);
        for (const commoditySpecificationType of commoditySpecificationTypeJson) {
            //选择新增商品规格类别
            $(".window-add-commodity-specifications select").append(`
<option specification-type-id="${commoditySpecificationType.specificationTypeId}" value="${commoditySpecificationType.specificationTypeId}">
${commoditySpecificationType.specificationTypeName}</option>`)
        }
    })
    let addCommodityFile = null;
    //上传详细图片
    $(".add-commodity-img").on("click", function (e) {
        e.preventDefault();
        // 创建并触发一个模拟的点击事件
        let clickEvent = new MouseEvent('click', {
            view: window,
            bubbles: true,
            cancelable: true
        });
        $('.upload-add-commodity-image')[0].dispatchEvent(clickEvent);
    })
    //上传商品参数
    $(".upload-add-commodity-image").on("change",function () {
        // 检查是否已选择视频文件
        if (!this.files || !this.files[0]) {
            return;
        }
        // 获取选中的文件信息
        let file = this.files[0];
        addCommodityFile = file;
        let fileName = file.name;
        let fileSize
            = file.size;
        let fileType = file.type;
        console.log(fileName)
        if (fileType.indexOf('image/') === 0 && fileSize < 500 * 1024 * 1024) {

        }else{
            // 将文件信息显示在页面上
            alert('请选择图片文件，且文件大小不能超过500MB！');
        }
    })
    $(".add-commodity-button").on("click",function () {
        let commodity = new Commodity();

        commodity.addCommodityImage(addCommodityFile).then(function (response) {
            let commodityJson = {
                commodityName:$(".window-add-commodity-name input").val(),
                commodityImages:response,
                keywords:$($(".window-add-commodity-keyword input")[1]).val(),
                commodityDescription:$(".window-add-commodity-description input").val(),
                commodityPrice:$(".window-add-commodity-price input").val(),
                commodityClass:$(".window-add-commodity-class option:selected").val()
            }
            let commoditySpecificationJson = {
                specificationName:$(".window-add-commodity-specifications input").val(),
                specificationTypeId:$(".window-add-commodity-specifications option:selected").val()
            }
            console.log(commodityJson)
            commodity.addCommodity(commodityJson,commoditySpecificationJson).then(res=>{
                console.log(res)
                location.reload()
            })
        });
    })
})